package com.niiwoo.civet.mobile.controller.bill;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.BillBaseDubboService;
import com.niiwoo.civet.account.dto.request.UserBillBaseRequestDTO;
import com.niiwoo.civet.account.dto.response.MonthBillResponseDTO;
import com.niiwoo.civet.account.dto.response.NiiwooBillRespDTO;
import com.niiwoo.civet.account.dto.response.UserBillBaseResponseDTO;
import com.niiwoo.civet.account.enums.*;
import com.niiwoo.civet.account.service.NiiwooBillDubboService;
import com.niiwoo.civet.account.service.bill.UserBillStatisticsDubboService;
import com.niiwoo.civet.base.enums.BorrowProjectTypeEnum;
import com.niiwoo.civet.base.enums.ChannelCodeEnum;
import com.niiwoo.civet.mobile.service.bill.InvokeTradeService;
import com.niiwoo.civet.mobile.service.bill.detail.BillDetailStrategyHandle;
import com.niiwoo.civet.mobile.vo.request.bill.BillFilterTypeRequest;
import com.niiwoo.civet.mobile.vo.request.bill.MonthBillRequestVO;
import com.niiwoo.civet.mobile.vo.request.bill.PageUserBillForDateRequest;
import com.niiwoo.civet.mobile.vo.request.bill.UserBillDetailRequest;
import com.niiwoo.civet.mobile.vo.response.bill.MonthBillResponseVO;
import com.niiwoo.civet.mobile.vo.response.bill.PageUserBillForDateResponse;
import com.niiwoo.civet.mobile.vo.response.bill.UserBillDetailResponse;
import com.niiwoo.civet.mobile.vo.response.bill.UserBillFilterTypeReponse;
import com.niiwoo.civet.trade.dto.common.ProjectDTO;
import com.niiwoo.civet.trade.dto.response.InvestStatusResponseDTO;
import com.niiwoo.civet.trade.dto.response.creditor.CreditorConfigDTO;
import com.niiwoo.civet.trade.dto.response.intelligenceInvest.ProjectPackageResponseDTO;
import com.niiwoo.civet.trade.enums.LoanTypeEnum;
import com.niiwoo.civet.trade.service.creditor.CreditorConfigDubboService;
import com.niiwoo.civet.trade.service.creditor.CreditorRightsDubboService;
import com.niiwoo.civet.trade.service.invest.InvestOrderDubboService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.tripod.base.utils.DateUtils;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Strings;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户账单
 * Created by xiaoyingping on 2018/10/29.
 */
@RestController
@RequestMapping("/userBills")
@Api(tags = "用户账单(肖应平)", description = "/userBills")
@Slf4j
public class UserBillController {

    @Autowired
    private BillDetailStrategyHandle billDetailStrategyHandle;
    @Autowired
    private InvokeTradeService invokeTradeService;


    @Reference(version = "1.0.0")
    private BillBaseDubboService billBaseDubboService;
    @Reference(version = "1.0.0")
    private NiiwooBillDubboService niiwooBillDubboService;
    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;
    @Reference(version = "1.0.0")
    private CreditorRightsDubboService creditorRightsDubboService;
    @Reference(version = "1.0.0")
    private InvestOrderDubboService investOrderDubboService;
    @Reference(version = "1.0.0")
    private CreditorConfigDubboService creditorConfigDubboService;
    @Reference(version = "1.0.0")
    private UserBillStatisticsDubboService userBillStatisticsDubboService;


    @PostMapping("/queryFilterType")
    @ApiOperation("获取用户账单筛选类型列表")
    @AuthIgnore
    public Result<List<UserBillFilterTypeReponse>> queryBillFilterTypes(@RequestBody BillFilterTypeRequest request){
        List<UserBillFilterTypeReponse> result = new ArrayList<>();
        result.add(new UserBillFilterTypeReponse("", "全部"));

        List<UserBillFilterTypeReponse> list = Stream.of(BillBusinessTypeEnum.values())
                .map(e -> new UserBillFilterTypeReponse(e.getCode(), e.getDesc()))
                .collect(Collectors.toList());
        result.addAll(list);

        //判断是否有请求特殊入口
        Integer enterType = request.getEnterType();
        if(Objects.nonNull(enterType)){
            if(enterType == 1){
                //H5纯投资流程要去掉"借款"、还款
                List<String> disableList = Arrays.asList(BillBusinessTypeEnum.LEND.getCode(), BillBusinessTypeEnum.REPAYMENT.getCode());
                result = result.stream().filter(e -> !disableList.contains(e.getCode())).collect(Collectors.toList());
            }
        }

        //是否已开启债转功能
        CreditorConfigDTO creditorConfigDTO = creditorConfigDubboService.getCreditorConfigs();
        if(Objects.isNull(creditorConfigDTO) || creditorConfigDTO.getCreditorSwitch() == 0){
            //未开启，不显示“转让”项
            result = result.stream().filter(e -> !e.getCode().equals(BillBusinessTypeEnum.CREDITOR_TRANSFER.getCode())).collect(Collectors.toList());
        }

        return Result.with(result);
    }


    @PostMapping("/pageForDate")
    @ApiOperation("分页查询用户账单[按日期]")
    public Result<PageUserBillForDateResponse> pageUserBillsForDate(@RequestBody @Valid PageUserBillForDateRequest request){
        PageUserBillForDateResponse response = new PageUserBillForDateResponse();
        long startTime = System.currentTimeMillis();
        String userId = PrincipalContext.getUserId();
        log.info("interface start, interfaceName:pageUserBillsForDate, userId:{}, request:{}", userId, JSON.toJSONString(request));

        //调用dubbo接口查询账单列表
        UserBillBaseRequestDTO userBillBaseRequestDTO = this.buildQueryParamsForPageByDate(userId, request);
        PageResponseDTO<UserBillBaseResponseDTO> pageResponseDTO = billBaseDubboService.pageUserBillBaseList(userBillBaseRequestDTO);
        long a = System.currentTimeMillis();
        log.info("a================={}",a - startTime);

        //转换账单数据对象并按月进行分组
        List<PageUserBillForDateResponse.MonthData> monthDataList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(pageResponseDTO.getItems())){
            monthDataList = this.transUserBillBaseGroupByMonth(pageResponseDTO.getItems());
        }else if(!Strings.isNullOrEmpty(request.getYearMonth())) {
            //如果查询结果为空，并且指定了查询哪一个月，则特殊处理（应前端要求返回的monthData不能为null）
            PageUserBillForDateResponse.MonthData monthData = response.new MonthData();
            monthData.setYearMonth(request.getYearMonth());
            monthData.setBillDatas(Collections.EMPTY_LIST);
            monthDataList.add(monthData);
        }
        response.setItems(monthDataList);
        long b = System.currentTimeMillis();
        log.info("b================={}",b - a);

        //统计并设置账单总金额和月度总金额
        this.statisticsBillTotalAmount(request.getFilterType(),userBillBaseRequestDTO, response);
        long c = System.currentTimeMillis();
        log.info("c================={}",c - b);

        //组装返回结果
        response.setTotalCount(pageResponseDTO.getTotalCount());
        response.setTotalPage(pageResponseDTO.getTotalPage());
        long endTime = System.currentTimeMillis();
        log.info("interface end, costTime:{} ms, interfaceName:pageUserBillsForDate, userId:{}, request:{}", endTime - startTime, userId, JSON.toJSONString(request));
        return Result.with(response);
    }


    @PostMapping("/查询账单详细信息")
    @ApiOperation("查询账单详细信息的接口描述")
    @AuthIgnore
    public Result<UserBillDetailResponse> aaaaaaaaa(@RequestBody @Valid UserBillDetailRequest request){
        return null;
    }

    @PostMapping("/detail")
    @ApiOperation("查询账单详细信息")
    public Result<String> queryBillDetail(@RequestBody @Valid UserBillDetailRequest request){
        long startTime = System.currentTimeMillis();
        String userId = PrincipalContext.getUserId();
        log.info("interface start, interfaceName:queryBillDetail, userId:{}, request:{}", userId, JSON.toJSONString(request));

        //调用dubbo查询账单Base和账单流水
        Long billBaseId = request.getBillId();
        UserBillBaseResponseDTO userBillBaseResponseDTO = billBaseDubboService.queryUserBillBase(userId, billBaseId);
        List<NiiwooBillRespDTO> niiwooBillList = billBaseDubboService.listBillListByBillBaseId(billBaseId, userId);
        OrderTypeEnum orderTypeEnum = OrderTypeEnum.enumOf(userBillBaseResponseDTO.getOrderType());
        BillBusinessTypeEnum billBusinessTypeEnum = orderTypeEnum.getBillBusinessTypeEnum();

        //查询账单的资金明细
        UserBillDetailResponse response = new UserBillDetailResponse();
        List<UserBillDetailResponse.AmountItem> amountItemList = niiwooBillList.stream()
                .sorted(Comparator.comparing(NiiwooBillRespDTO::getSecondSortCode))//排序
                .map(niiwooBill -> {
                    UserBillDetailResponse.AmountItem amountItem = response.new AmountItem();
                    amountItem.setCode(niiwooBill.getSecondSortCode());
                    amountItem.setName(BillSecondSubjectEnum.getEnumByCode(niiwooBill.getSecondSortCode()).getCodeName() + "(元)");
                    amountItem.setAmountDesc(niiwooBill.getAmount().abs().toString());
                    return amountItem;
                }).collect(Collectors.toList());

        //组装返回结果
        response.setBillId(userBillBaseResponseDTO.getBillBaseId());
        response.setBillTitle(this.genertateBillTileForList(userBillBaseResponseDTO));
        response.setStatus(userBillBaseResponseDTO.getStatus());
        response.setStatusDesc(BillStatusEnum.getEnumByCode(response.getStatus()).getDesc());

        if(InoutTypeEnum.OUT_TYPE.getType().equals(userBillBaseResponseDTO.getInoutType())){
            response.setAmount(userBillBaseResponseDTO.getAmount().negate());
        }else {
            response.setAmount(userBillBaseResponseDTO.getAmount());
        }

        response.setAmountItems(amountItemList);
        response.setSpecialItems(new ArrayList<>());
        response.setTradeType(billBusinessTypeEnum.getCode());
        response.setTradeTypeDesc(billBusinessTypeEnum.getDesc());
        response.setBillTime(userBillBaseResponseDTO.getCreateTime());
        response.setRequestNo(userBillBaseResponseDTO.getRequestNo());
        response.setProjectId(userBillBaseResponseDTO.getProjectId());
        response.setOrderId(userBillBaseResponseDTO.getOrderId());

        //按业务类型显示不同的账单详情内容
        String detailJsonStr = billDetailStrategyHandle.buildBillDetail(userBillBaseResponseDTO, niiwooBillList, response);
        log.info("detailJsonStr=============={}", detailJsonStr);

        //返回接口
        long endTime = System.currentTimeMillis();
        log.info("interface end, costTime:{} ms, interfaceName:queryBillDetail, userId:{}, request:{}", endTime - startTime, userId, JSON.toJSONString(request));
        return Result.with(detailJsonStr);
    }

    @PostMapping("/queryMonthBill")
    @ApiOperation("月账单")
    public Result<MonthBillResponseVO> queryMonthBill(@RequestBody @Valid MonthBillRequestVO monthBillRequestVO) {
        long startTime = System.currentTimeMillis();
        String userId = PrincipalContext.getUserId();
        log.info("interface start, interfaceName:queryMonthBill, userId:{}, request:{}", userId, JSON.toJSONString(monthBillRequestVO));

        MonthBillResponseVO responseVO = new MonthBillResponseVO();
        String yearMonthBill = monthBillRequestVO.getBillMonth();
        MonthBillResponseDTO monthBillResponseDTO = niiwooBillDubboService.statisticalUserMonthBill(userId,yearMonthBill);

        //投资
        responseVO.setInvestAmount(monthBillResponseDTO.getInvestAmount());
        responseVO.setInvestCount(monthBillResponseDTO.getInvestCount());
        responseVO.setReceivablePrincipalAmount(monthBillResponseDTO.getReceivablePrincipalAmount());
        responseVO.setReceivableInterest(monthBillResponseDTO.getReceivableInterest());

        //奖励
        responseVO.setCouponReward(monthBillResponseDTO.getCouponReward());
        responseVO.setPlatformReward(monthBillResponseDTO.getPlateformReward());
        responseVO.setRecommendReward(monthBillResponseDTO.getRecommendReward());

        //借款还款
        responseVO.setBorrowAmount(monthBillResponseDTO.getBorrowAmount());
        responseVO.setRefundPrincipalAmount(monthBillResponseDTO.getRefundPrincipalAmount());
        responseVO.setRefundInterest(monthBillResponseDTO.getRefundInterest());
        responseVO.setPenalty(monthBillResponseDTO.getRefundPenalty());

        //充值提现
        responseVO.setRechargeAmount(monthBillResponseDTO.getRechargeAmount());
        responseVO.setWithdrawAmount(monthBillResponseDTO.getWithdrawAmount());

        //费用
        responseVO.setTransferFee(monthBillResponseDTO.getTransferFee());
        responseVO.setWithdrawFee(monthBillResponseDTO.getWithdrawFee());
        responseVO.setInvestFee(monthBillResponseDTO.getInvestFee());
        responseVO.setLoanFee(monthBillResponseDTO.getLoanFee());
        responseVO.setGuaranteeFee(monthBillResponseDTO.getGuaranteeFee());

        //是否已开启债转功能
        CreditorConfigDTO creditorConfigDTO = creditorConfigDubboService.getCreditorConfigs();
        if(Objects.isNull(creditorConfigDTO) || creditorConfigDTO.getCreditorSwitch() == 0){
            //未开启
            responseVO.setIsOpenedTransferService(false);
        }else {
            responseVO.setIsOpenedTransferService(true);
        }

        long endTime = System.currentTimeMillis();
        log.info("interface end, costTime:{} ms, interfaceName:queryMonthBill, userId:{}, request:{}", endTime - startTime, userId, JSON.toJSONString(monthBillRequestVO));
        return Result.with(responseVO);
    }



    //组装向dubbo查询的条件
    private UserBillBaseRequestDTO  buildQueryParamsForPageByDate(String userId, PageUserBillForDateRequest request){
        UserBillBaseRequestDTO userBillBaseRequestDTO = new UserBillBaseRequestDTO();
        userBillBaseRequestDTO.setUserId(userId);
        userBillBaseRequestDTO.setChannelCode(ChannelCodeEnum.APP.getChanelCode());
        userBillBaseRequestDTO.setIsVisibleEnum(BillIsVisibleEnum.SHOW);
        userBillBaseRequestDTO.setPageNumber(request.getPageNumber());
        userBillBaseRequestDTO.setPageSize(request.getPageSize());

        //通过筛选类型指定账单的OrderType
        String billBusinessType = request.getFilterType();
        if(!Strings.isNullOrEmpty(billBusinessType)){
            List<Byte> orderTypes = BillBusinessTypeEnum.getOrderTypes(billBusinessType);
            if(!CollectionUtils.isEmpty(orderTypes)){
                userBillBaseRequestDTO.setOrderTypes(orderTypes);
            }
            if(BillBusinessTypeEnum.BACKSPACE.getCode().equals(billBusinessType)){
                //退款
                userBillBaseRequestDTO.setIsBackSpace(true);
            }
        }

        //指定查询哪个月
        String queryYearMonth = request.getYearMonth();
        if(!Strings.isNullOrEmpty(queryYearMonth)){
            DateTime yearMonthDateTime = new DateTime(DateUtils.parseDateFromString(queryYearMonth,"yyyyMM"));
            DateTime minDateTime = yearMonthDateTime.withDayOfMonth(1).withTimeAtStartOfDay();//月初
            DateTime maxDateTime = minDateTime.plusMonths(1).minusSeconds(1);//月末
            userBillBaseRequestDTO.setStartTime(minDateTime.toDate());
            userBillBaseRequestDTO.setEndTime(maxDateTime.toDate());
        }

        return userBillBaseRequestDTO;
    }

    //转换账单数据对象并按月进行分组
    private List<PageUserBillForDateResponse.MonthData> transUserBillBaseGroupByMonth(List<UserBillBaseResponseDTO> userBillBaseList){
        List<PageUserBillForDateResponse.BillData> billDataList = userBillBaseList.stream().map(dto -> {
            PageUserBillForDateResponse.BillData billData = new PageUserBillForDateResponse().new BillData();
            billData.setBillId(dto.getBillBaseId());
            if(InoutTypeEnum.OUT_TYPE.getType().equals(dto.getInoutType())){
                billData.setAmount(dto.getAmount().negate());
            }else {
                billData.setAmount(dto.getAmount());
            }

            billData.setBillTitle(this.genertateBillTileForList(dto));
            if(Objects.nonNull(dto.getBackSourceBillId())){
                billData.setBillHeadImgUrl(BillBusinessTypeEnum.BACKSPACE.getHeadImgUrl());
            }else {
                billData.setBillHeadImgUrl(OrderTypeEnum.enumOf(dto.getOrderType()).getBillBusinessTypeEnum().getHeadImgUrl());
            }
            billData.setStatus(dto.getStatus());
            if(Objects.nonNull(dto.getBackSourceBillId())){
                billData.setStatus(BillStatusEnum.SUCCESS.getValue());
            }
            billData.setStatusDesc(BillStatusEnum.getEnumByCode(billData.getStatus()).getDesc());
            billData.setBillTime(dto.getCreateTime());
            billData.setYearMonth(new DateTime(dto.getCreateTime()).toString("yyyyMM"));
            return billData;
        }).collect(Collectors.toList());

        //按月进行分组、排序
        Map<String, List<PageUserBillForDateResponse.BillData>> billDataMap = billDataList.stream().collect(Collectors.groupingBy(PageUserBillForDateResponse.BillData::getYearMonth));
        List<PageUserBillForDateResponse.MonthData> monthDataList = billDataMap.entrySet().stream().map(e ->{
            PageUserBillForDateResponse.MonthData monthData = new PageUserBillForDateResponse().new MonthData();
            monthData.setYearMonth(e.getKey());
            monthData.setBillDatas(e.getValue());
            return monthData;
        }).sorted(Comparator.comparing(PageUserBillForDateResponse.MonthData::getYearMonth).reversed()).collect(Collectors.toList());

        return monthDataList;
    }



    //统计账单的总金额和月底总金额
    private void statisticsBillTotalAmount(String billBusinessType, UserBillBaseRequestDTO requestDTO, PageUserBillForDateResponse response){
        /** =============账单总金额===========*/
        if(Strings.isNullOrEmpty(billBusinessType) || BillBusinessTypeEnum.OTHER == BillBusinessTypeEnum.enumOf(billBusinessType)){
            //没有筛选项查询条件或者为“其它”：不展示账单总金额
        }else{
            //有筛选项查询条件:展示筛选项的总金额
            if(!BillBusinessTypeEnum.BACKSPACE.getCode().equals(billBusinessType)){
                requestDTO.setStatus(BillStatusEnum.SUCCESS.getValue());//查询退款时要排除状态
            }

            UserBillBaseRequestDTO totalAmountRequest = new UserBillBaseRequestDTO();
            BeanUtils.copyProperties(requestDTO, totalAmountRequest);

            //总收入和总支出
            totalAmountRequest.setInOutType(InoutTypeEnum.IN_TYPE.getType());
            BigDecimal inputTotalAmount = billBaseDubboService.totalAmount(totalAmountRequest);
            totalAmountRequest.setInOutType(InoutTypeEnum.OUT_TYPE.getType());
            BigDecimal payTotalAmount = billBaseDubboService.totalAmount(totalAmountRequest);

            //总金额=总收入-总支出
            PageUserBillForDateResponse.AmountItem totalAmountItem = response.new AmountItem();
            totalAmountItem.setName(BillBusinessTypeEnum.enumOf(billBusinessType).getDesc());
            totalAmountItem.setAmount(inputTotalAmount.subtract(payTotalAmount).abs());

            DecimalFormat df = new DecimalFormat(",###,##0.00"); //保留两位小数
            StringBuffer totalAmountSbf = new StringBuffer("总计:").append(BillBusinessTypeEnum.enumOf(billBusinessType).getDesc())
                                                                   .append(df.format(inputTotalAmount.subtract(payTotalAmount).abs()))
                                                                   .append("元");
            response.setTotalAmountDesc(totalAmountSbf.toString());
        }

        /** =============月度总金额===========*/
        for (PageUserBillForDateResponse.MonthData monthData : response.getItems()) {
            monthData.setMonthAmountItems(new ArrayList<>());

            //计算每个月的开始时间和结束时间
            DateTime yearMonthDateTime = new DateTime(DateUtils.parseDateFromString(monthData.getYearMonth(),"yyyyMM"));
            DateTime minDateTime = yearMonthDateTime.withDayOfMonth(1).withTimeAtStartOfDay();//月初
            DateTime maxDateTime = minDateTime.plusMonths(1).minusSeconds(1);//月末

            //统计每个月的总收入、总支出
            UserBillBaseRequestDTO totalAmountRequest = new UserBillBaseRequestDTO();
            BeanUtils.copyProperties(requestDTO, totalAmountRequest);
            totalAmountRequest.setStartTime(minDateTime.toDate());
            totalAmountRequest.setEndTime(maxDateTime.toDate());


            //判断是否有筛选项用来决定怎么展示月度账单总金额
            if(Strings.isNullOrEmpty(billBusinessType)){
                //没有筛选项查询条件：展示月度账单总收入、总支出
                totalAmountRequest.setInOutType(InoutTypeEnum.IN_TYPE.getType());
                BigDecimal inputTotalAmount = billBaseDubboService.totalAmount(totalAmountRequest);//收入
                totalAmountRequest.setInOutType(InoutTypeEnum.OUT_TYPE.getType());
                BigDecimal payTotalAmount = billBaseDubboService.totalAmount(totalAmountRequest);//支出

                PageUserBillForDateResponse.AmountItem amountItem = response.new AmountItem();
                amountItem.setName("收入");
                amountItem.setAmount(inputTotalAmount.abs());
                monthData.getMonthAmountItems().add(amountItem);

                amountItem = response.new AmountItem();
                amountItem.setName("支出");
                amountItem.setAmount(payTotalAmount.abs());
                monthData.getMonthAmountItems().add(amountItem);
            }else {
                //有筛选项查询条件:展示筛选项的月度账单总金额
                totalAmountRequest.setOrderTypes(BillBusinessTypeEnum.getOrderTypes(billBusinessType));
                totalAmountRequest.setInOutType(InoutTypeEnum.IN_TYPE.getType());
                BigDecimal inputTotalAmount = billBaseDubboService.totalAmount(totalAmountRequest);//收入
                totalAmountRequest.setInOutType(InoutTypeEnum.OUT_TYPE.getType());
                BigDecimal payTotalAmount = billBaseDubboService.totalAmount(totalAmountRequest);//支出

                PageUserBillForDateResponse.AmountItem amountItem = response.new AmountItem();
                amountItem.setName(BillBusinessTypeEnum.enumOf(billBusinessType).getDesc());
                amountItem.setAmount(inputTotalAmount.subtract(payTotalAmount).abs());
                monthData.getMonthAmountItems().add(amountItem);
            }
        }
    }


    //生成列表账单标题
    private String genertateBillTileForList(UserBillBaseResponseDTO dto){
        String orderIdStr = "";
        if(!Strings.isNullOrEmpty(dto.getOrderId()) && dto.getOrderId().length() >2 ){
            orderIdStr = "(" + StringUtils.right(dto.getOrderId(), 4) + ")";//只展示订单id的后4位,-1不展示
        }

        OrderTypeEnum orderTypeEnum = OrderTypeEnum.enumOf(dto.getOrderType());
        BillBusinessTypeEnum billBusinessTypeEnum = orderTypeEnum.getBillBusinessTypeEnum();

        BorrowProjectTypeEnum projectTypeEnum = null;
        if(Objects.nonNull(dto.getProjectType())){
            projectTypeEnum = BorrowProjectTypeEnum.enumOf(dto.getProjectType());
        }

        LoanTypeEnum loanTypeEnum = null;
        if(Objects.nonNull(dto.getLoanType())){
            loanTypeEnum = LoanTypeEnum.enumOf(dto.getLoanType());
        }

        StringBuffer sbf = new StringBuffer();
        if(BillBusinessTypeEnum.INVEST == billBusinessTypeEnum){
            if(BorrowProjectTypeEnum.TRANSFER_OF_CREDIT == projectTypeEnum){
                InvestStatusResponseDTO investStatusResponseDTO = investOrderDubboService.queryInvestOrderDetail(Long.valueOf(dto.getOrderId()));
                ProjectDTO projectDTO = projectDubboService.selectProjectById(investStatusResponseDTO.getProjectId());
                sbf.append("债权投资-").append(this.getBillLoanTypeDesc(LoanTypeEnum.enumOf(projectDTO.getLoanType()))).append(orderIdStr);
            }else {
                sbf.append("投资");
                if(OrderTypeEnum.ZNT_INVEST == orderTypeEnum){
                    sbf.append("-").append(this.getProjectPackageTitle(dto.getProjectPackageId()));
                }else if(Objects.nonNull(loanTypeEnum)){
                    sbf.append("-").append(this.getBillLoanTypeDesc(loanTypeEnum)).append(orderIdStr);
                }else {
                    sbf.append(orderIdStr);
                }
            }
        }else if(BillBusinessTypeEnum.CREDITOR_TRANSFER == billBusinessTypeEnum){
            sbf.append("转让债权");
        }else if(BillBusinessTypeEnum.RECEIVED_REPAYMENT == billBusinessTypeEnum){
            sbf.append("回款");

            String investIdEndStr = "";
            if(Objects.nonNull(dto.getInvestId()) && dto.getInvestId() > 0){
                investIdEndStr = "(" + StringUtils.right(dto.getInvestId().toString(), 4) + ")";
            }
            if(BorrowProjectTypeEnum.TRANSFER_OF_CREDIT == projectTypeEnum){
                sbf.append("-债转标").append(investIdEndStr);
            }else {
                if(!dto.getProjectId().equals(dto.getProjectPackageId())){
                    //智能投
                    sbf.append("-").append(this.getProjectPackageTitle(dto.getProjectPackageId()));
                }else {
                    if(Objects.nonNull(loanTypeEnum)){
                        sbf.append("-").append(this.getBillLoanTypeDesc(loanTypeEnum)).append(investIdEndStr);
                    }else {
                        sbf.append(investIdEndStr);
                    }
                }
            }

        }else if(BillBusinessTypeEnum.LEND == billBusinessTypeEnum){
            sbf.append("借款");
            ProjectDTO projectDTO = projectDubboService.selectProjectById(dto.getProjectId());
            if(Objects.nonNull(projectDTO) && Objects.nonNull(projectDTO.getDeadline())){
                sbf.append("-").append(projectDTO.getDeadline()).append("期");
            }
        }else if(BillBusinessTypeEnum.REPAYMENT == billBusinessTypeEnum){
            sbf.append("还款");
            if(Objects.nonNull(dto.getCurrentPeriod()) && Objects.nonNull(dto.getTotalPeriods())){
                sbf.append("-").append(dto.getCurrentPeriod()).append("/").append(dto.getTotalPeriods()).append("期");
            }
        }else if(BillBusinessTypeEnum.RECHARGE == billBusinessTypeEnum){
            if(OrderTypeEnum.RECHARGE_AUTO == orderTypeEnum){
                sbf.append("代扣充值");
            }else {
                sbf.append("余额充值");
            }
        }else if(BillBusinessTypeEnum.WITHDRAW == billBusinessTypeEnum){
            sbf.append("余额提现");
        }else if(BillBusinessTypeEnum.PRIZED == billBusinessTypeEnum){
            List<NiiwooBillRespDTO> niiwooBillRespDTOList = billBaseDubboService.listBillListByBillBaseId(dto.getBillBaseId(), dto.getUserId());
            if(niiwooBillRespDTOList.size() > 0){
                sbf.append(BillSecondSubjectEnum.getEnumByCode(niiwooBillRespDTOList.get(0).getSecondSortCode()).getCodeName());
            }else {
                sbf.append("奖励");
            }
        }else{
            if(Objects.nonNull(orderTypeEnum) && OrderTypeEnum.NONE != orderTypeEnum){
                if(OrderTypeEnum.USER_RED.getCode().equals(dto.getOrderType())){
                    List<NiiwooBillRespDTO> niiwooBillRespDTOList = billBaseDubboService.listBillListByBillBaseId(dto.getBillBaseId(), dto.getUserId());
                    if(niiwooBillRespDTOList.size() > 0){
                        sbf.append(BillSecondSubjectEnum.getEnumByCode(niiwooBillRespDTOList.get(0).getSecondSortCode()).getCodeName());
                    }
                }else {
                    sbf.append(orderTypeEnum.getDesc());
                }
            }else {
                sbf.append("其它");
            }
        }

        //退款
        if(Objects.nonNull(dto.getBackSourceBillId())){
            sbf.insert(0,"退款【").append("】");
        }

        return sbf.toString();
    }

    private String getProjectPackageTitle(Long packageId){
        ProjectPackageResponseDTO projectPackageResponseDTO = invokeTradeService.queryProjectPackageInfo(packageId);
        if(Objects.nonNull(projectPackageResponseDTO)){
            return projectPackageResponseDTO.getTitle();
        }

        return "";
    }


    private String getBillLoanTypeDesc(LoanTypeEnum loanTypeEnum){
//        List<LoanTypeEnum> mortgageList = Arrays.asList(LoanTypeEnum.HOUSE_MORTGAGE_LOAN, LoanTypeEnum.VEHICLE_MORTGAGE_LOAN);
//        if(mortgageList.contains(loanTypeEnum)){
//            return  "抵押标";
//        }else {
//            return  "信用标";
//        }

        return "散标";
    }


}
